"""
@author: Zhang Wenzhou
@file: stuinfo.py
@time: 2023/2/24 0024 10:53:36
"""
# 路由需要绑到核心对象上去
# from __main__ import ss_app
#
# @ss_app.route("/")
# def index():
#     return "stuinfo / index"


# current_app代表当前生成的app
# from flask import current_app
#
# @current_app.route("/")
# def index():
#     return "stuinfo / index"

## 使用蓝图管理路由
# render_template 渲染函数
from flask import Blueprint, request, render_template
from model.user import StuInfo
from model import db
from libs.response import response_data

# 生成蓝图对象
stu_bp = Blueprint("student", __name__, url_prefix="/v1")

# 把路由绑到蓝图对象
@stu_bp.route("/")
def index():
    return "this is student info index"

'''
# 写一个接口 “/register”
@stu_bp.route("/register", methods=['POST'])
def register():
    try:
        # 通过接收json格式的数据，获取用户名、性别、年龄
        name = request.json['name']
        sex = request.json['sex']
        age = request.json['age']

        # 存入数据库
        import pymysql
        # 打开数据库连接
        db = pymysql.connect(host="192.168.152.134",
                             port=3306,
                             user="sctl",
                             password="123456",
                             database="flask")
        # 使用 cursor() 方法创建一个游标对象
        cursor = db.cursor()
        # 使用 execute()  方法执行 SQL 查询
        cursor.execute(f"insert into stuinfo(name,sex,age) values('{name}','{sex}',{age})")
        # 提交数据
        db.commit()
        # 关闭数据库连接
        db.close()
        # 成功提示“注册完成”，中间发生异常或失败返回“注册失败”
        return "注册完成"
    except Exception as e:
        return "注册失败"
'''

# ORM object relationship map（对象关系映射）
# 不和复杂的sql打交道，直接通过操控数据模型的对象，来实现对数据库的操作
# sqlalchemy -- 不在flask使用也行 -- flask-sqlalchemy
@stu_bp.route("/register", methods=["POST"])
def register():
    try:
        message = request.json
        name = message['name']
        sex = message['sex']
        age = message['age']
    #     rom   类--表    对象--一行记录
        stu = StuInfo(name=name,
                      sex=sex,
                      age=age)
        db.session.add(stu)     # 要修改的对象加入暂存区
        db.session.commit()     # 提交暂存区里的对象
        return response_data(message="添加信息成功！")
    except:
        return response_data(code=1,message="添加信息失败！")

@stu_bp.route("/modify", methods=["PUT"])
def modify():
    try:
        id = request.args.get("id")
        # 查询:找到要修改的对象
        stu = StuInfo.query.get(int(id))
        # 找不到对象就返回None
        if stu:
            stu.name = request.json.get("name")
            stu.sex = request.json.get("sex")
            stu.age = request.json.get("age")
            db.session.add(stu)
            db.session.commit()
            return response_data(message="修改信息成功")
    except:
        return response_data(code=1, message="修改信息失败！")

@stu_bp.route("/delete", methods=["DELETE"])
def delete():
    try:
        id = request.args.get("id")
        stu = StuInfo.query.get(int(id))
        if stu:
            db.session.delete(stu)
            db.session.commit()
            return response_data(message="删除信息成功")
    except:
        return response_data(code=1, message="删除信息失败！")

"""
TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a StuInfo.
从数据库里获取到的信息，需要进行数据序列化
"""


@stu_bp.route("/get", methods=["GET"])
def get():
    # 能获取到id返回一个，获取不到id，返回所有
    try:
        id = request.args.get("id")
        stu = StuInfo.query.get(int(id))
        print(stu)
        # StuInfo.query.all()
        if stu:
            # tmp = {"id": stu.id, "name": stu.name, "sex": stu.sex, "age": stu.age}
            # return tmp
            # return stu.to_json()
            return response_data(message="获取数据成功", data=dict(stu))
        else:
            return response_data(message="查询不到")
    except:
        stu_lst = []
        for i in StuInfo.query.all():
            # stu_lst.append(i.to_json())
            stu_lst.append(dict(i))
        return response_data(code=1, message="获取数据失败！", data=stu_lst)


# 返回页面 #
@stu_bp.route("/html")
def html():
    id = request.args.get("id")
    stu = StuInfo.query.get(int(id))
    if stu:
        return render_template("index.html", content=stu)